from urllib.parse import urlencode
from rest_framework.pagination import PageNumberPagination


def get_from_to(page, limit):
    """根据page和limit计算ORM中切片的值"""
    _from = (page - 1) * limit
    _to = _from + limit
    return _from, _to


def get_previous_page(request, page=1, **kwargs):
    """生成前一页的URL"""
    if page <= 1:
        return None
    base_url = request.build_absolute_uri('?')
    kwargs['page'] = page - 1
    for k, v in kwargs.items():
        if isinstance(v, bool):
            kwargs[k] = str(v).lower()
    return base_url + '?' + urlencode(kwargs)


def get_next_page(request, total, page=1, limit=10, **kwargs):
    """生成下一页的URL"""
    if page * limit >= total:
        return None
    base_url = request.build_absolute_uri('?')
    kwargs['page'] = page + 1
    kwargs['limit'] = limit
    for k, v in kwargs.items():
        if isinstance(v, bool):
            kwargs[k] = str(v).lower()
    return base_url + '?' + urlencode(kwargs)


class PageSizePagination(PageNumberPagination):
    page_size = 10
    page_size_query_param = 'size'
